package cc.fs.zhihuapp.utils;

import android.hardware.Camera;
import android.hardware.camera2.CameraDevice;
import android.media.MediaRecorder;
import android.util.Log;
import android.view.SurfaceHolder;

/**
 * Created by fostion on 2015/11/7.
 */
public class RecordVideo implements MediaRecorder.OnErrorListener {

    private final String TAG = "-RecordVideo-";
    private MediaRecorder mediaRecorder;
    private SurfaceHolder surfaceHolder;
    private Camera camera;

    public RecordVideo(Camera camera,SurfaceHolder surfaceHolder) {
        this.camera = camera;
        this.surfaceHolder = surfaceHolder;
    }

    public boolean start(String filePath) {
        try {
            if (mediaRecorder == null) {
                camera.unlock();
                mediaRecorder = new MediaRecorder();
                mediaRecorder.setOnErrorListener(this);//监听错误
                mediaRecorder.setCamera(camera);//设置摄像头
                mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);    //音频获取源
                mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//视频获取源
                mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);  //视频格式 mp4
                mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);  //视频编码格式
                mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);  //音频编码格式
                mediaRecorder.setOutputFile(filePath);  //保存文件夹
                mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface()); //预览view
                mediaRecorder.setVideoSize(640, 480);//视频分辨率
                mediaRecorder.setVideoEncodingBitRate(5 * 1024 * 1024); //编码bit率提高清晰度
                mediaRecorder.setMaxFileSize(10 * 1024 * 1024);//设置文件最大值
                mediaRecorder.prepare(); //准备
                mediaRecorder.start();   // 录制
                Log.d("TAG", "开始录制视频");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public void stop() {
        try {
            if (mediaRecorder != null) {
                if (camera != null) camera.lock();
                mediaRecorder.setOnErrorListener(null);
                mediaRecorder.setPreviewDisplay(null);
                mediaRecorder.stop();
                mediaRecorder.reset();
                mediaRecorder.release();
                mediaRecorder = null;
                Log.d("TAG", "停止释放录制资源");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(MediaRecorder mr, int what, int extra) {
        try {
            if (mr != null) {
                mr.reset();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
